<template>
    <a-card hoverable style="width: 300px">
        <template #cover>
            <img alt="example" :src="userStore.avtarSrc" />
        </template>
        <template #actions>
            <setting-outlined key="setting" />
            <edit-outlined key="edit" />

            <el-tooltip content="上传头像" placement="top" hide-after="0" effect="light">
                <UploadOutlined @click="uploadAvatar" />
                <input type="file" />
            </el-tooltip>

            <el-tooltip content="退出登录" placement="top" hide-after="0" effect="light">
                <LogoutOutlined @click="logout" />
            </el-tooltip>
        </template>
        <a-card-meta :title="userStore.name" description="个人介绍">
            <template #avatar>
                <a-avatar :src="userStore.avtarSrc" />
            </template>
        </a-card-meta>
    </a-card>
</template>
<script setup>
import { SettingOutlined, EditOutlined, UploadOutlined, LogoutOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user';
import axios from 'axios';
const userStore = useUserStore()
const router = useRouter()
const logout = () => {
    localStorage.removeItem('token')
    ElMessage.success('已退出登录')
    router.replace('/login')
}

const input = document.createElement('input');
input.type = 'file';
input.style.display = 'none';
const reader = new FileReader();

input.addEventListener('change', event => {
    let file = event.target.files[0];
    const formData = new FormData();
    formData.append('id', userStore.id);
    formData.append('avatar', file);
    axios(
        {
            method: 'post',
            url: '/avatar',
            headers: {
                'token': localStorage.getItem('token')
            },
            data: formData
        }
    ).then(
        res => {
            if (res.data.status === '1') {
                ElMessage.success('上传成功')
                reader.readAsDataURL(file);
                reader.onload = () => {
                    userStore.avtarSrc = reader.result;
                }
            } else {
                ElMessage.error(res.data.msg)
            }
        }
    )
});

const uploadAvatar = () => {
    input.click();
}

</script>
  
  